package com.deng.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deng.api.entity.AuthUser;
import com.deng.api.entity.SysMenu;
import com.deng.api.entity.SysRole;
import com.deng.api.mapper.SysMenuMapper;
import com.deng.api.mapper.SysRoleMapper;
import com.deng.api.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库认证的Service实现
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String uname) throws UsernameNotFoundException {

        AuthUser user =  sysUserMapper.getUserByUserName(uname);
        // 为空或者禁用了
        if (user == null || user.getEnabled().equals("false")){
            return null;
        }
        //如果可以用，把角色信息放入到user中
        List<SysRole> roles = sysRoleMapper.getRolesByUid(user.getId());
        //对应的权限获取
        List<SysMenu> menus = new ArrayList<>();
        for (SysRole role:roles) {
            sysMenuMapper.getMenusByRid(role.getId()).stream().forEach(menu -> {
                //去重
                if (!menus.contains(menu)){
                    menus.add(menu);
                }
            });
        }
        user.setRoles(roles);
        user.setMenus(menus);
        return user;
    }
}
